package com.heima.admin.gateway.filter;

import com.heima.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component//加入ioc
@Order(value = 0)//设置过滤器执行的顺序
public class AuthFilter implements GlobalFilter {



    /**
     * 验证token
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();//获取请求
        ServerHttpResponse response = exchange.getResponse();//获取响应
        String path = request.getPath().toString();//获取请求路径
        if (path.contains("/login/in")) {
            //登录请求直接放行
            return chain.filter(exchange);
        }
        //验证token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            //设置没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            log.info("未登录!");
            return response.setComplete();
        }
        try {
            //取出登录的用户id  放入请求头  这里超时或token不符合要求都会抛异常
            String userId = JwtUtils.getInfoFromToken(token).getUserId().toString();
            ServerHttpRequest newRequest = request.mutate()
                            .headers(httpHeaders -> httpHeaders.add("userId",userId))
                            .build();
            //重新设置请求
            exchange.mutate().request(newRequest);
            String id = request.getHeaders().getFirst("userId");
            log.info("用户的id为: {}",id);
            //放行
            return chain.filter(exchange);
        } catch (Exception e) {
            log.info("token验证失败!");
            //设置没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }
}
